;
(function() {
  new Vue({
    el: '#bill-tmp',
    data: {
      templateId:null,
      projectId:hlUrlUtil.GetQueryString('projectId'),
      contractId:hlUrlUtil.GetQueryString('contractId'),
      billId:hlUrlUtil.GetQueryString('billId'),
      template:[],
      selectedTmp:{'name':null},
      pageStyle:{},
      pageLeft:[],
      pageRight:[],
      pageTop:[],
      pageBottom:[],
      templateValue: [],
      headPerData: [],
      footerPerData:[],
      tbTitleLength:0,
      tbHead:[],
      tbContent:[],
      watermarkData:[],
      watermarkStyle:[]
    },
    filters:{
      formatUndefined: function(item) {
        if (!item && item != 0) return '--'
        return item
      }
    },
    methods: {
      getTemplateList(){
        var self = this;
        // 默认模版索引  如果没有默认展示第一项
        var defaultIndex = -1;

        hlhttp.get({
          url:'project/print_template_list',
          data:{project_id:self.projectId},
          success:function(data){
            self.template = data;
            data.forEach((el,i) => {
              if(el.isDefault == 'Y'){
                self.selectedTmp = {'name':el.name,id:el.id}
                defaultIndex = i;
              }
            })
            // 如果没有默认模版  则显示第一项数据
            if(defaultIndex == -1)  self.selectedTmp = {'name':data[0].name,id:data[0].id}
            self.selectTmp(self.selectedTmp.id,self.selectedTmp.name)
          }
        })
      },

      getTemplateName() {
        var self = this;
        hlhttp.get({
          url: 'bill/print_template',
          data: { template_id: self.templateId },
          success: function(data) {

            // 页边距
            var pageData = data.page[0];
            self.pageStyle = {
              'paddingLeft':pageData.eleMarginLeft + 'px',
              'paddingRight':pageData.eleMarginRight + 'px',
              'paddingTop':pageData.eleMarginTop + 'px',
              'paddingBottom':pageData.eleMarginBottom + 'px'
            }
            // 水印图片
            data.image.forEach((el,i) => {
              var obj = {
                'url':el.eleValue ,
                'width':el.eleWidth + '',
                'height':el.eleHeight + '',
                'opacity':el.eleOpacity + '',
                'left':el.eleMarginLeft + '',
                'right':el.eleMarginRight + '',
                'top':el.eleMarginTop + '',
                'bottom':el.eleMarginBottom + ''
              }
              var objStyle = {
                'url':el.eleValue ,
                'width':el.eleWidth + 'px' ,
                'height':el.eleHeight + 'px',
                'opacity':el.eleOpacity + 'px',
                'left':el.eleMarginLeft ? el.eleMarginLeft + 'px' : null,
                'right':el.eleMarginRight ? el.eleMarginRight + 'px' : null,
                'top':el.eleMarginTop ? el.eleMarginTop + 'px' : null,
                'bottom':el.eleMarginBottom ? el.eleMarginBottom + 'px' : null
              }
              self.watermarkData.push(obj)
              self.watermarkStyle.push(objStyle)
            })
            // 头部
            var headData = [];
            if (data.head.length) headData = hlArrayUtil.splitInToTwoimensionalArray(data.head, 3);

            // 去除掉空格占位符
            var tmpHeadArr = [];
            headData.forEach((el, i) => {
              var tmpArr = [];
              var blankNum = 0;

              el.forEach((item, index) => {
                if (item.eleType === 'sys') item['eleVal'] = self.matchTemplateVal(item.eleValue)
                if (item.eleType === 'ph') blankNum++;
              })

              // 该循环用来分配每个要展示的模块的所占比例
              el.forEach((item,index) => {
                if(blankNum == 0) item['width'] = 'w33'
                if(blankNum == 1 && item.eleType == 'ph') item['width'] = 'w00'
                if(blankNum == 1 && item.eleType != 'ph') item['width'] = 'w50'
                if(blankNum == 2 && item.eleType == 'ph') item['width'] = 'w00'
                if(blankNum == 2 && item.eleType != 'ph') item['width'] = 'w100'
                if(blankNum == 3) item['width'] = 'w33'
                tmpArr.push(item)
              })
              tmpHeadArr.push(tmpArr)

            })
            self.headPerData = tmpHeadArr;
            console.log(self.headPerData)
            // 收费表格
            var tmpContentArr = data.content;
            self.tbTitleLength = 0;
            data.content.forEach((el,i) => {
              if(el.eleShow == 'Y') self.tbTitleLength++;
            })
            self.tbHead = tmpContentArr;

            var allTbContent = self.templateValue.expenses;
            var tmpTbContent = [];
            var payedTotalPrice = 0,receiveTotalPrice = 0,totalPrice = 0,receiveOriginalTotalPrice = 0,receiveDiscountTotalPrice = 0;

            allTbContent.forEach((el,i) => {
              var arr = [];
              self.tbHead.forEach((item,index) => {
                let eleValue = item.eleValue
                arr.push({'value':el[eleValue],'eleShow':item.eleShow})

                if(eleValue == 'amountReceive'){
                  totalPrice = totalPrice + Number(el.amountReceive)
                }
                if(eleValue == 'amountPayed'){
                  payedTotalPrice = payedTotalPrice + Number(el.amountPayed)
                }
                if(eleValue == 'amountTpay'){
                  receiveTotalPrice = receiveTotalPrice + Number(el.amountTpay)
                }
                if (eleValue == 'amountReceiveOriginal'){
                  receiveOriginalTotalPrice = receiveOriginalTotalPrice + Number(el.amountReceiveOriginal)
                }
                if (eleValue == 'amountReceiveDiscount'){
                  receiveDiscountTotalPrice = receiveDiscountTotalPrice + Number(el.amountReceiveDiscount)
                }
              })
              tmpTbContent.push(arr)
            })


            // 新增一行计算总价钱
            var lastArr = [];
            self.tbHead.forEach((item,index) => {
              let eleValue = item.eleValue, eleValueArr = ['name','amountReceive','amountPayed','amountTpay','amountReceiveOriginal','amountReceiveDiscount']
              if(eleValueArr.indexOf(eleValue) == -1){
                lastArr.push({ 'value': '', 'eleShow': item.eleShow })
              }
              // 费项那一列新增一行显示合计
              if (eleValue == 'name') lastArr.push({'value': '合计','eleShow': item.eleShow})
              if(eleValue == 'amountReceive') lastArr.push({'value': totalPrice.toFixed(2) , 'eleShow':item.eleShow})
              if(eleValue == 'amountPayed') lastArr.push({'value': payedTotalPrice.toFixed(2) , 'eleShow':item.eleShow})
              if(eleValue == 'amountTpay') lastArr.push({'value': receiveTotalPrice.toFixed(2) , 'eleShow':item.eleShow})
              if(eleValue == 'amountReceiveOriginal') lastArr.push({'value': receiveOriginalTotalPrice.toFixed(2) , 'eleShow':item.eleShow})
              if(eleValue == 'amountReceiveDiscount') lastArr.push({'value': receiveDiscountTotalPrice.toFixed(2) , 'eleShow':item.eleShow})
            })
            tmpTbContent.push(lastArr)
            self.tbContent = tmpTbContent;
            // 尾部
            var footerData = [];
            if(data.tail.length) footerData = hlArrayUtil.splitInToTwoimensionalArray(data.tail, 3);
            // 去除掉空格占位符
            var tmpFooterArr = [];

            footerData.forEach((el, i) => {
              var tmpArr = [];
              var blankNum = 0;

              el.forEach((item, index) => {
                if (item.eleType === 'sys') item['eleVal'] = self.matchTemplateVal(item.eleValue)
                if (item.eleType === 'ph') blankNum++;
              })

              // 该循环用来分配每个要展示的模块的所占比例
              el.forEach((item,index) => {
                if(blankNum == 0) item['width'] = 'w33'
                if(blankNum == 1 && item.eleType == 'ph') item['width'] = 'w00'
                if(blankNum == 1 && item.eleType != 'ph') item['width'] = 'w50'
                if(blankNum == 2 && item.eleType == 'ph') item['width'] = 'w00'
                if(blankNum == 2 && item.eleType != 'ph') item['width'] = 'w100'
                if(blankNum == 3) item['width'] = 'w33'
                tmpArr.push(item)
              })
              tmpFooterArr.push(tmpArr)

            })
            self.footerPerData = tmpFooterArr;
          }
        })
      },

      getTemplateVal() {
        var self = this;
        hlhttp.get({
          url: 'bill/print_data',
          data: {
            contract_id: self.contractId,
            bill_id:self.billId
          },
          success: function(data) {
            self.templateValue = data;
            self.getTemplateList()
          }
        })
      },

      selectTmp(id,name){
        this.selectedTmp = {'name':name,'id':id}
        this.templateId = id;
        this.getTemplateName()
      },

      matchTemplateVal(code) {
        console.log(code)
        var result;
        var elementVal = this.templateValue.elementVal;
        console.log(elementVal)
        console.log(code)
        switch (code) {
          case 'projectName':
            result = elementVal.projectName
            break;
          case 'projectName':
            result = elementVal.projectName
            break;
          case 'contractMCode':
            result = elementVal.contractMCode
            break;
          case 'contractCCode':
            result = elementVal.contractCCode
            break;
          case 'contractName':
            result = elementVal.contractName
            break;
          case 'contractSignDate':
            result = elementVal.contractSignDate
            break;
          case 'rentBeginDate':
            result = elementVal.rentBeginDate
            break;
          case 'rentEndDate':
            result = elementVal.rentEndDate
            break;
          case 'rentDuration':
            result = elementVal.rentDuration
            break;
          case 'customerName':
            result = elementVal.customerName
            break;
          case 'rentResources':
            result = elementVal.rentResources
            break;
          case 'rentUnitAcreage':
            result = elementVal.rentUnitAcreage
            break;
          case 'rentWpCount':
            result = elementVal.rentWpCount
            break;
          case 'rentStCount':
            result = elementVal.rentStCount
            break;
          case 'billNo':
            result = elementVal.billNo
            break;
          case 'billDuration':
            result = elementVal.billDuration
            break;
          case 'currentDate':
            result = elementVal.currentDate
            break;
          case 'currentTime':
            result = elementVal.currentTime
            break;
          case 'currentOperator':
            result = elementVal.currentOperator
            break;
          case 'bankName':
            result = elementVal.bankName
            break;
          case 'bankAccount':
            result = elementVal.bankAccount
            break;
          case 'accountName':
            result = elementVal.accountName
            break;
          default:
            result = elementVal[code]
        }

        return result;
      },

      exportPDF(){
        var doctypeHtml = '<!DOCTYPE html>' +
              '<html lang="en">' +
              '<head>' +
                '<meta charset="UTF-8"></meta>' +
                '<link rel="stylesheet" href="http://dev.fenzhitech.com/wbuild-saas-pc/styles/libs/bootstrap_3.3.7.css"></link>' +
                '<link rel="stylesheet" href="http://dev.fenzhitech.com/wbuild-saas-pc/styles/libs/font.css"></link>' +
                '<link rel="stylesheet" href="http://dev.fenzhitech.com/wbuild-saas-pc/styles/app/blue/blue.min.css"></link>' +
              '</head>'+
              '<body>'

        $(document).on('click', '.export-btn', function() {
          var ctxHtml = $('#print-content').html()
          var modelHtml = doctypeHtml + ctxHtml + '</body></html>'

          $.ajax({
            url:convert2pdfApi,
            type: 'post',
            data:{'html_str':modelHtml},
            headers:{token:Cookies.get("token")},
            success:function(data){
              window.open(data.url)
            }
          })
        })
      },

      print(){
        function callPrinter(content, options) {
          if (!content) window.print();else {
            var iframe = document.createElement('iframe');
            iframe.setAttribute('style', 'display: none');
            document.body.appendChild(iframe);
            var subWindow = iframe.contentWindow;
            var $content;
            if (typeof content === 'string') $content = content
            subWindow.document.body.innerHTML = $content;
            setTimeout(function () {
              subWindow.print();
              document.body.removeChild(iframe);
            }, options && options.delay || 100);
          }
        }

        console.log('22');
        var doctypeHtml = '<!DOCTYPE html>' +
              '<html lang="en">' +
              '<head>' +
                '<meta charset="UTF-8"></meta>' +
                '<link rel="stylesheet" href="http://dev.fenzhitech.com/wbuild-saas-pc/styles/libs/bootstrap_3.3.7.css"></link>' +
                '<link rel="stylesheet" href="http://dev.fenzhitech.com/wbuild-saas-pc/styles/libs/font.css"></link>' +
                '<link rel="stylesheet" href="http://dev.fenzhitech.com/wbuild-saas-pc/styles/app/blue/blue.min.css"></link>' +
              '</head>'+
              '<body>'

        var ctxHtml = document.querySelector('#print-content').innerHTML;
        var modelHtml = doctypeHtml + ctxHtml + '</body></html>'

        callPrinter(modelHtml)

        // $.ajax({
        //   url:convert2pdfApi,
        //   type: 'post',
        //   data:{ 'html_str':modelHtml },
        //   headers:{ token: Cookies.get("token") },
        //   success:function(data){
        //     // $('#printIframe').attr( 'src', data.url )
        //     window.open(data.url)
        //     window.print();
        //   }
        // })

        // 打印处理前dom存储
        // var bdHtml = window.document.body.innerHTML;
        // var ctxHtml = document.querySelector('#print-content').innerHTML;
        //
        // window.document.body.innerHTML = doctypeHtml + ctxHtml + '</body></html>';
        // window.print();
        // window.document.body.innerHTML = bdHtml;
      }
    },
    created:function(){
      this.getTemplateVal()
    },
    mounted: function() {
      var pageHeight = document.querySelector('.ahei').style.height;
      hlSelectUi()
      this.exportPDF()
    }
  })
}())
